from sqlalchemy import create_engine
engine = create_engine('sqlite:///db',connect_args={'check_same_thread': False}, echo=True)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base   
Base = declarative_base()

from sqlalchemy import Column, Integer, String

def get_session():
    db_session = sessionmaker(bind=engine)
    session = db_session()
    return session


session = get_session()

class  User(Base):
    __tablename__ = 'user02'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    password = Column(String)
    nickname = Column(String)
    
class question(Base):
    __tablename__ = 'question'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    detail = Column(String)

def init_db():
    Base.metadata.create_all(bind=engine);

init_db();#创建数据库

def add_user(name,password,nickname):
    try:
        q1=session.query(User).filter(User.name==name).one()
    except Exception as e:
        q1=None
        print(e)
    if q1:
        return False
    else:
        new_user = User(name=name,password=password,nickname=nickname)
        session.add(new_user)
        session.commit()
        return True
        
        
def change(user_info,opwd,npwd):
    u1=session.query(User).filter(User.name==user_info,User.password==opwd).one()
    if u1.password == opwd:
        u1.password = npwd
        session.add(u1)
        session.commit()
        return True
    else:
        return False
        
    
        
        

    
   

